package com.cuitrip.business.tripservice;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.cuitrip.business.login.ui.agreement.AgreementLayout;
import com.cuitrip.business.tripservice.model.ServiceInfo;
import com.cuitrip.business.tripservice.presenter.TripEditPresenter;
import com.cuitrip.business.tripservice.proxy.PriceProxy;
import com.cuitrip.business.tripservice.proxy.ServiceFormProxy;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.business.tripservice.ui.TripEditView;
import com.cuitrip.component.item.ItemLayout;
import com.cuitrip.component.para.ParaListView;
import com.cuitrip.component.para.model.ExistStylePara;
import com.cuitrip.component.para.model.FullStylePara;
import com.cuitrip.component.para.model.Para;
import com.cuitrip.component.para.model.TimPara;
import com.cuitrip.component.para.proxy.ParaProxy;
import com.cuitrip.service.R;
import com.cuitrip.util.ResourceUtil;
import com.cuitrip.util.text.TextProxy;
import com.jakewharton.rxbinding.widget.RxTextView;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.rx.TextChangeTargetVisibilitySubscriber;
import com.lab.utils.ImageHelper;
import com.lab.utils.Utils;
import com.lab.widget.WordCountView;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 编辑主页面
 * Created by ak on 16/2/15.
 */
public class TripEditMainFragment extends CustomUiFragment implements TripEditView {

    @Bind(R.id.trip_name)
    protected WordCountView mTripTitle;
    @Bind(R.id.edit_hint)
    protected IconTextView mTitleEditHint;
    @Bind(R.id.address_layout)
    protected ItemLayout mAddressLayout;
    @Bind(R.id.highlight_layout)
    protected ItemLayout mHighLightLayout;
    @Bind(R.id.highlight_para_list)
    protected ParaListView mHighLightParaListView;
    @Bind(R.id.description_title_layout)
    protected ItemLayout mDescLayout;
    @Bind(R.id.description_content)
    protected LinearLayout descriptionContent;
    @Bind(R.id.description_text)
    protected TextView descriptionText;
    @Bind(R.id.main_pic)
    protected ImageView descriptionImage;
    @Bind(R.id.other_instruction_layout)
    protected ItemLayout mOtherInstructionLayout;
    @Bind(R.id.other_instruction_para_list)
    protected ParaListView mOtherInstructionParaView;
    @Bind(R.id.main_pic_layout)
    protected View mMainPicLayout;
    @Bind(R.id.main_title_layout)
    protected ItemLayout mMainPicTitleLayout;
    @Bind(R.id.demand_layout)
    protected ItemLayout mDemandLayout;
    @Bind(R.id.demand_para_list)
    protected ParaListView mDemandParaView;
    @Bind(R.id.pay_layout)
    protected ItemLayout mPayLayout;
    @Bind(R.id.pay_para_list)
    protected ParaListView mPayParaListView;
    @Bind(R.id.agreement_layout)
    protected AgreementLayout agreementLayout;
    @Bind(R.id.commit)
    protected TextView commitView;
    @Bind(R.id.full_content)
    protected View mFullContent;
    @Bind(R.id.scroll_view)
    ScrollView mScrollView;
    @Bind(R.id.name_layout)
    View mNameLayout;
    private View mContentView;
    private TripEditActivity.ContentMode contentMode = TripEditActivity.ContentMode.NEW_MODE;


    private TripEditPresenter mTripEditPresenter;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle data = getArguments();
        ServiceInfo serviceInfo = null;
        if (data != null) {
            if (data.getBoolean(TripEditActivity.SERVICE_EDIT_MODE_KEY, false)) {
                contentMode = TripEditActivity.ContentMode.EDIT_MODE;
            }
            if (data.containsKey(ServiceInfo.KEY)) {
                serviceInfo = (ServiceInfo) data.getSerializable(ServiceInfo.KEY);
            }
        }
        mTripEditPresenter = new TripEditPresenter();
        mTripEditPresenter.attachView(this);
        mTripEditPresenter.initServiceInfo(serviceInfo, contentMode);
    }

    @Override
    public void onDestroy() {
        mTripEditPresenter.detachView();
        super.onDestroy();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = super.onCreateView(inflater, container, savedInstanceState, R.layout.page_create_trip);
        return mContentView;
    }


    @Override
    public void initView() {
        ButterKnife.bind(this, mContentView);
        EditText editText = mTripTitle.getEditView();
        editText.setGravity(Gravity.CENTER_HORIZONTAL);
        editText.setHintTextColor(getResources().getColor(R.color.ganshi_ded8d7));
        editText.setPadding(getResources().getDimensionPixelOffset(R.dimen.ct_width_padding), Utils.dp2pixel(10), getResources().getDimensionPixelOffset(R.dimen.ct_width_padding), Utils.dp2pixel(10));
        editText.setTextSize(17.f);
        editText.setTextColor(getResources().getColor(R.color.ct_black));
        commitView.setEnabled(agreementLayout.isChecked());
        agreementLayout.changeMode(AgreementLayout.CREATE_SERVICE_MODE);
    }

    @Override
    public void initListener() {
        RxTextView
                .textChangeEvents(mTripTitle.getEditView())
                .subscribe(addSubscriber(new TextChangeTargetVisibilitySubscriber().setTarget(mTitleEditHint, false)));
        agreementLayout.setAgreeCheckCallback(new AgreementLayout.AgreeCheckCallback() {
            @Override
            public void onAgreeCheckChanged(boolean isChecked) {
                commitView.setEnabled(isChecked);
            }
        });

    }

    @Override
    public void initData() {
        mTripEditPresenter.renderUi();
    }

    @OnClick(R.id.pay_layout)
    public void navigatePayLayout() {
        mTripEditPresenter.navigateToPayInstruction(getHostActivity());
    }

    @OnClick(R.id.address_layout)
    public void clickCity() {
        mTripEditPresenter.navigateToSelectCity(this);
    }

    @OnClick(R.id.highlight_layout)
    public void navigateHightLight() {
        mTripEditPresenter.navigateToHighLight(getHostActivity(), this);
    }

    @OnClick(R.id.description_title_layout)
    public void clickDescription() {
        mTripEditPresenter.navigateToDescription(getHostActivity(), this);
    }

    @OnClick(R.id.other_instruction_layout)
    public void navigateOtherInstruction() {
        mTripEditPresenter.navigateOtherInstruction(getHostActivity(), this);
    }

    @OnClick(R.id.demand_layout)
    public void navigateDemandLayout() {
        mTripEditPresenter.navigate2Demand(getHostActivity(), this);
    }

    @OnClick(R.id.main_pic_layout)
    public void chooseMainPic() {
        mTripEditPresenter.chooseMainImagePic(this);
    }

    @OnClick(R.id.commit)
    public void commitTrip() {
        mTripEditPresenter.commitTrip(getTitle());
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }

    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig config = new CustomUiConfig();
        if (contentMode.equals(TripEditActivity.ContentMode.EDIT_MODE)) {
            config.mTopbarMiddleAreaName = getResources().getString(R.string.operation_edit);
        } else {
            config.mTopbarMiddleAreaName = getResources().getString(R.string.trip_operation_create);
        }
        config.mTopbarLeftAreaName = getString(R.string.back_icon);
        config.mTopbarRightAreaName = getString(R.string.operation_preview);
        config.mRightStyle = CustomUiConfig.AreaStyle.TEXT_STYLE;
        return config;
    }

    @Override
    public void onTopbarLeftPress() {
        backPress();
    }

    private void backPress() {
        mTripEditPresenter.onLeftPage(getTitle());
    }

    public String getTitle() {
        return mTripTitle.getEditView().getText().toString().trim();
    }

    @Override
    public void onTopbarRightPress() {
        mTripEditPresenter.preview(getTitle());
    }

    @Override
    public void showLoadingDialog() {
        showNoCancelDialog();
    }

    @Override
    public void hideLoadingDialog() {
        hideNoCancelDialog();
    }

    @Override
    public void finishPage() {
        getHostActivity().finish();
    }

    @Override
    public void renderTitle(ServiceInfo serviceInfo) {
        mTripTitle.setText(serviceInfo.getName());
    }

    @Override
    public void renderLocation(ServiceInfo serviceInfo) {
        StringBuilder stringBuilder = new StringBuilder();
        if (TextUtils.isEmpty(serviceInfo.getAddress())) {
            stringBuilder.append(getString(R.string.trip_attribute_location_desc_1));
        } else {
            stringBuilder.append(serviceInfo.getAddress());
        }
        mAddressLayout.setleftText(stringBuilder.toString());
    }

    @Override
    public void renderHighLight(ServiceInfo serviceInfo) {
        List<Para> paraList = new ArrayList<>();
        if (!TextUtils.isEmpty(serviceInfo.getHighLight())) {
            CharSequence[] valueList = ParaProxy.getInstance().getParaArray(serviceInfo.getHighLight());
            for (CharSequence charSequence : valueList) {
                Para para = new Para(charSequence);
                paraList.add(para);
            }
        }
        String cateString = serviceInfo.toCateString();
        if (!TextUtils.isEmpty(cateString)) {
            TimPara timPara = new TimPara(cateString);
            paraList.add(timPara);
        }
        setHighLightTitle(!paraList.isEmpty());
        mHighLightParaListView.setTextColor(R.color.ct_black);
        mHighLightParaListView.setParas(paraList);
    }

    @Override
    public void renderDescription(ServiceInfo serviceInfo) {
        if (!TextUtils.isEmpty(serviceInfo.getServiceDescript())) {
            descriptionContent.setVisibility(View.VISIBLE);

            if (!TextUtils.isEmpty(serviceInfo.getDescptWithnoPic())) {
                descriptionText.setText(serviceInfo.getDescptWithnoPic());
                descriptionText.setVisibility(View.VISIBLE);
            } else {
                descriptionText.setVisibility(View.GONE);
            }
            mDescLayout.setleftText(getString(R.string.trip_attribute_description));
            mDescLayout.setBottomLineStyle(ItemLayout.CONTENT);
        } else {
            mDescLayout.setleftText(getString(R.string.trip_attribute_description_desc_1));
            descriptionContent.setVisibility(View.GONE);
            mDescLayout.setBottomLineStyle(ItemLayout.FULL);
        }
    }

    @Override
    public void renderMainPic(ServiceInfo serviceInfo) {
        if (TextUtils.isEmpty(serviceInfo.getBackPic())) {
            mMainPicTitleLayout.setleftText(ResourceUtil.getString(R.string.trip_attribute_cover_photo_desc));
            descriptionImage.setVisibility(View.GONE);
        } else {
            mMainPicTitleLayout.setleftText(ResourceUtil.getString(R.string.trip_attribute_cover_photo));
            descriptionImage.setVisibility(View.VISIBLE);
            ImageHelper.displayCtImage(serviceInfo.getBackPic(), descriptionImage, null);
        }
    }

    @Override
    public void renderMainPic(Bitmap bitmap) {
        mMainPicTitleLayout.setleftText(ResourceUtil.getString(R.string.trip_attribute_cover_photo));
        descriptionImage.setImageBitmap(bitmap);
    }

    @Override
    public void renderOtherNotes(ServiceInfo serviceInfo) {
        List<ExistStylePara> paraList = new ArrayList<ExistStylePara>();
        int existNum = 0;
        ExistStylePara serviceNoticePara = new ExistStylePara(getString(R.string.trip_attribute_advice));
        if (!TextUtils.isEmpty(serviceInfo.otherNotes.getServiceNotice())) {
            serviceNoticePara.setIsExist(true);
            paraList.add(serviceNoticePara);
            existNum++;
        }

        ExistStylePara safeTipsPara = new ExistStylePara(getString(R.string.trip_attribute_safety));
        if (!TextUtils.isEmpty(serviceInfo.otherNotes.getServiceSafeTips())) {
            safeTipsPara.setIsExist(true);
            paraList.add(safeTipsPara);
            existNum++;
        }

        ExistStylePara wearTipsPara = new ExistStylePara(getString(R.string.trip_attribute_outfit));
        if (!TextUtils.isEmpty(serviceInfo.otherNotes.getServiceWearTips())) {
            wearTipsPara.setIsExist(true);
            paraList.add(wearTipsPara);
            existNum++;
        }


        ExistStylePara weatherTipsPara = new ExistStylePara(getString(R.string.trip_attribute_weather));
        if (!TextUtils.isEmpty(serviceInfo.otherNotes.getUnexpectedWeather())) {
            weatherTipsPara.setIsExist(true);
            paraList.add(weatherTipsPara);
            existNum++;
        }


        if (existNum == 0) {
            paraList.clear();
            mOtherInstructionLayout.setleftText(getString(R.string.trip_group_additional_info));
            mOtherInstructionLayout.setBottomLineStyle(ItemLayout.FULL);
        } else {
            mOtherInstructionLayout.setleftText(getString(R.string.trip_group_additional_info));
            mOtherInstructionLayout.setBottomLineStyle(ItemLayout.CONTENT);
        }
        mOtherInstructionParaView.setTextColor(R.color.ct_black);
        mOtherInstructionParaView.setParas(paraList);
    }

    @Override
    public void renderDemands(ServiceInfo serviceInfo) {
        List<FullStylePara> paraList = new ArrayList<>();
        int existNum = 0;

        FullStylePara preOrderPara = new FullStylePara(getString(R.string.trip_attribute_advance));
        if (serviceInfo.getPreOrderDays() != 0) {
            preOrderPara.setHeadColor(R.color.ct_black);
            existNum++;
            String text = TextProxy.getInstance().formatWithSingleAndMore(serviceInfo.getPreOrderDays(), R.string.trip_attribute_advance_value_one, R.string.trip_attribute_advance_value_more);
            preOrderPara.setContent(text);
            paraList.add(preOrderPara);
        }


        FullStylePara bestTimePara = new FullStylePara(getString(R.string.trip_attribute_duration));
        if (!TextUtils.isEmpty(serviceInfo.getServiceTime())) {
            existNum++;
            bestTimePara.setHeadColor(R.color.ct_black);
            String text = TextProxy.getInstance().formatWithSingleAndMore(serviceInfo.getServiceTime(), R.string.trip_attribute_duration_value_one, R.string.trip_attribute_duration_value_more);
            bestTimePara.setContent(text);
            paraList.add(bestTimePara);
        }


        FullStylePara personNumPara = new FullStylePara(getString(R.string.trip_attribute_capacity));
        if (serviceInfo.getMinBuyerNum() != 0 && serviceInfo.getMaxbuyerNum() != 0) {
            existNum++;
            personNumPara.setHeadColor(R.color.ct_black);
            //TODO
            personNumPara.setContent(TripDemandInstructionActivity.bindPersonNum(serviceInfo.getMinBuyerNum(), serviceInfo.getMaxbuyerNum()));
            paraList.add(personNumPara);
        }


        FullStylePara meetPlacePara = new FullStylePara(getString(R.string.trip_attribute_meet));
        if (!TextUtils.isEmpty(serviceInfo.getMeetingPlace())) {
            existNum++;
            meetPlacePara.setContent(serviceInfo.getMeetingPlace());
            meetPlacePara.setHeadColor(R.color.ct_black);
            paraList.add(meetPlacePara);
        }

        if (existNum == 0) {
            paraList.clear();
            mDemandLayout.setleftText(getString(R.string.trip_group_book));
            mDemandLayout.setBottomLineStyle(ItemLayout.FULL);
        } else {
            mDemandLayout.setleftText(getString(R.string.trip_group_book));
            mDemandLayout.setBottomLineStyle(ItemLayout.CONTENT);
        }

        mDemandParaView.setParas(paraList);
    }

    private void setHighLightTitle(boolean hasValue) {
        if (hasValue) {
            mHighLightLayout.setleftText(getString(R.string.trip_attribute_highlight));
            mHighLightLayout.setBottomLineStyle(ItemLayout.CONTENT);
        } else {
            mHighLightLayout.setleftText(getString(R.string.trip_attribute_highlight_desc_1));
            mHighLightLayout.setBottomLineStyle(ItemLayout.FULL);
        }
    }


    @Override
    public void renderPayInfo(ServiceInfo serviceInfo) {
        List<Para> paraList = new ArrayList<>();

        int existNum = 0;
        FullStylePara priceTypePara = new FullStylePara(getString(R.string.price_attribute_type));
        priceTypePara.setHeadColor(R.color.ct_black);
        if (!TextUtils.isEmpty(serviceInfo.getPriceType())) {
            existNum++;
            int index = Integer.parseInt(serviceInfo.getPriceType());
            priceTypePara.setContent(getResources().getStringArray(R.array.pay_ways_array)[index]);
            paraList.add(priceTypePara);
        }


        FullStylePara pricePara = new FullStylePara(getString(R.string.price));
        pricePara.setHeadColor(R.color.ct_black);
        if (!TextUtils.isEmpty(serviceInfo.getPrice())) {
            existNum++;
            pricePara.setContent(PriceProxy.getInstance().priceFormatText(serviceInfo.getPriceType(), serviceInfo.getMoneyType(), serviceInfo.getPrice()));
            paraList.add(pricePara);
        }


        ExistStylePara feeCover = new ExistStylePara(getString(R.string.price_group_detail));
        feeCover.setHeadColor(R.color.ct_black);
        if (!TextUtils.isEmpty(serviceInfo.getFeeInclude()) && !TextUtils.isEmpty(serviceInfo.getFeeExclude())) {
            existNum++;
            feeCover.setIsExist(true);
            paraList.add(feeCover);
        }

        if (existNum == 0) {
            paraList.clear();
            mPayLayout.setleftText(getString(R.string.price_set));
            mPayLayout.setBottomLineStyle(ItemLayout.FULL);
        } else {
            mPayLayout.setleftText(getString(R.string.price));
            mPayLayout.setBottomLineStyle(ItemLayout.CONTENT);
        }
        mPayParaListView.setParas(paraList);
    }

    @Override
    public boolean performInvalidAction(ServiceFormProxy.InValidType inValidType) {

        switch (inValidType) {
            case TITLE:
                int[] titleArray = new int[2];
                mTripTitle.getLocationOnScreen(titleArray);
                mScrollView.scrollTo(titleArray[0], titleArray[1]);
                Utils.shakeView(mNameLayout);
                break;
            case ADDRESS:
                int[] addressArray = new int[2];
                mAddressLayout.getLocationOnScreen(addressArray);
                mScrollView.scrollTo(addressArray[0], addressArray[1]);
                Utils.shakeView(mAddressLayout);
                break;
            case HIGHLIGHT:
                int[] highArray = new int[2];
                mHighLightLayout.getLocationOnScreen(highArray);
                mScrollView.scrollTo(highArray[0], highArray[1]);
                Utils.shakeView(mHighLightLayout);
                break;
            case DESCRIPTION:
                int[] descArray = new int[2];
                mDescLayout.getLocationOnScreen(descArray);
                mScrollView.scrollTo(descArray[0], descArray[1]);
                Utils.shakeView(mDescLayout);
                break;
            case OTHERS:
                int[] otherArray = new int[2];
                mOtherInstructionLayout.getLocationOnScreen(otherArray);
                mScrollView.scrollTo(otherArray[0], otherArray[1]);
                Utils.shakeView(mOtherInstructionLayout);
                break;
            case DEMAND:
//                int[] demandArray = new int[2];
//                mDemandLayout.getLocationOnScreen(demandArray);
//                mScrollView.scrollTo(demandArray[0], demandArray[1]);
                Utils.shakeView(mDemandLayout);
                break;
            case PAY:
//                int[] positionArray = new int[2];
//                mPayLayout.getLocationOnScreen(positionArray);
//                mScrollView.scrollTo(positionArray[0], positionArray[1]);
                Utils.shakeView(mPayLayout);
                break;
            case MAIN_PIC:
                int[] mainPicArray = new int[2];
                mMainPicLayout.getLocationOnScreen(mainPicArray);
                mScrollView.scrollTo(mainPicArray[0], mainPicArray[1]);
                Utils.shakeView(mMainPicLayout);
            default:
                return true;
        }
        return false;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        mTripEditPresenter.handleActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public boolean onBackPressed(boolean fromKey) {
        backPress();
        return true;
    }

    @Override
    public Context getContext() {
        return getHostActivity();
    }
}
